import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,
      me: this,
      watchs: [],
      //模型
      models: {
        //模型

        collectionPoint: {
          ...typeClassName["collectionPoint"],
        },
        equipment: {
          ...typeClassName["equipment"],
        },
        techOverLimit: {
          ...typeClassName["techOverLimit"],
        },
        labOverLimit: {
          ...typeClassName["labOverLimit"],
        },
      },
      equipmentTreeData: [],
      dataSet: {
        //数据集
        treeData: [],
        treeCurrentData: [],
        formData: {},
        tableData: [],
        tableData1: [],
        tableData2: [],
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      console.log(comp, "comp");
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      this.init();
      if (process.env.NODE_ENV === "development") {
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    init() {
      this.getEquipTypeOptions();
      this.statisticsByEquip();
    },
    loadPage(pageNavigation, filter) {
      Promise.all([
        this.loadPage1(pageNavigation),
        this.loadPage2(pageNavigation),
      ]).then((res) => {
        this.dataSet.tableData = res[0].concat(res[1]);
        this.vms.mainTable.navigation.page.total =
          this.dataSet.tableData.length;
      });
    },
    statisticsByEquip() {
      this.$api.inspection.statisticsByEquip({}).then((res) => {
        let obj = {
          实验室参数: res.values.lab,
          工艺参数: res.values.tech,
        };
        this.barData.categories = res.equip;
        this.barData.values = res.values;
        this.lineData.categories = res.equip;
        this.lineData.values = res.values;
      });
    },
    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      if (this.dataSet.treeCurrentData.length > 0) {
        this.dataSet.formData = this._getModelTpl("collectionPoint");
        this._modalShow("createModal");
        this.dataSet.formData.values["sf_code"] = "";
        this.dataSet.formData.values["sf_name"] = "";
        this.dataSet.formData.values["equipmentTypeName"] =
          this.dataSet.treeCurrentData[0].data.sf_name;
        this.dataSet.formData.values["equipmentTypeCode"] =
          this.dataSet.treeCurrentData[0].data.id;
      } else {
        this.$Message.info("请选择设备");
      }

      // 这是一个整理接口数据JSON格式的方法
      // this.dataSet.formData.values["jobNumber"] = "";
      // this.dataSet.formData.values["peopleName"] = "";
      // this.dataSet.formData.values["phoneNumber"] = "";
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.formData = row;
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.formData = row;
    },
    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models.collectionPoint.clzs, [String(row.id)])
          .then((res) => {
            _this.models["collectionPoint"].clzs.records.splice(index, 1);
            _this.dataSet.tableData =
              _this.models["collectionPoint"].clzs.setValueRecords();
            _this.vms.mainTable.navigation.page.total--;
          });
      });
    },
    handleDeleteMultiple(selection) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = selection.map((item) => String(item.id));
        _this
          ._$deleteByIds(_this.models.collectionPoint.clzs, ids)
          .then((res) => {
            _this.vms.mainTable.navigation.page.pageNumber = 1;
            _this.loadPage(_this.vms.mainTable.navigation, {
              equipmentTypeCode: this.dataSet.formData.values.equipmentTypeCode,
            });
          });
      });
    },
    // 新增确认
    createModalOk(btn) {
      this._$validateAll([this.vms.createView], (valid) => {
        btn.loading = false;
        if (valid) {
          this.dataSet.formData.className =
            this.models.collectionPoint.className;
          this.dataSet.formData.type = this.models.collectionPoint.type;
          this.dataSet.formData.name = +new Date();

          this._$add(
            this.models["collectionPoint"].clz,
            this.dataSet.formData
          ).then((flag) => {
            this._modalClose("createModal");
            this._resetForm("createView");
            this.loadPage(this.vms.mainTable.navigation.page, {
              equipmentTypeCode: this.dataSet.formData.values.equipmentTypeCode,
            });
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    // 编辑确认
    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        btn.loading = false;
        if (valid) {
          this.models.collectionPoint.clz.setRecord(this.dataSet.formData);
          this.models.collectionPoint.clz.updateById().then((flag) => {
            if (flag) {
              this._modalClose("editModal");
              this._resetForm("editView");
              this.loadPage(this.vms.mainTable.navigation.page, {
                equipmentTypeCode:
                  this.dataSet.formData.values.equipmentTypeCode,
              });
            } else {
              this._modalClose("editModal");
            }
          });
        } else {
          btn.loading = false;
          this._$requireInfo();
        }
      });
    },
    treeSelect(item, data) {
      console.log(item, data);
      this.dataSet.treeCurrentData = data;
      this.loadPage(this.vms.mainTable.navigation.page, {
        equipmentTypeCode: item.id,
      });
    },
    getEquipTypeOptions() {
      let data = {
        className: this.models.equipment.className,
        type: this.models.equipment.type,
      };
      this.dataSet.treeData = [];
      this._$query(this.models.equipment.clzs, data).then((res) => {
        this.models.equipment.clzs.records.forEach((d) => {
          this.dataSet.treeData.push({
            id: d.id,
            parentId: "root",
            name: d.values.sf_name,
            sf_name: d.values.sf_name,
            sf_code: d.values.sf_code,
          });
        });
      });
    },
    loadPage1() {
      let newFilter = {
        className: this.models.techOverLimit.className,
        type: this.models.techOverLimit.type,
      };
      let filterString = this._$setFilteStr(newFilter, false);
      if (this.startTime != "") {
        filterString = filterString + " && " + this.dateOf;
      }
      return this._$query(
        this.models["techOverLimit"].clzs,

        filterString
      ).then((res) => {
        return (this.dataSet.tableData1 =
          this.models["techOverLimit"].clzs.valueRecords);
      });
    },
    loadPage2() {
      let newFilter = {
        className: this.models.labOverLimit.className,
        type: this.models.labOverLimit.type,
      };
      let filterString = this._$setFilteStr(newFilter, false);
      if (this.startTime != "") {
        filterString = filterString + " && " + this.dateOf;
      }
      return this._$query(
        this.models["labOverLimit"].clzs,

        filterString
      ).then((res) => {
        return (this.dataSet.tableData2 =
          this.models["labOverLimit"].clzs.valueRecords);
      });
    },
  },
};
